﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace BaseSyntax.ThreadTest
{
	public class AsyncRequest:ITest
	{
		public async Task AsyncTest()
		{
			string url = "https://www.google.com";
			Console.WriteLine("begin request: " + url);

			Task task = CreateTask(url);
			try
			{
				while (!task.Wait(100))
				{
					Console.Write(".");
				}
			}
			catch (AggregateException e)
			{
				Console.WriteLine(e);
				
			}
		}

		public Task CreateTask(string url)
		{
			StreamReader streamReader = null;
			
			WebRequest webRequest = WebRequest.Create(url);

			Task task = webRequest.GetResponseAsync()
				.ContinueWith(
					task1 =>
					{
						WebResponse webResponse = task1.Result;
						streamReader = new StreamReader(webResponse.GetResponseStream());
						return streamReader.ReadToEndAsync();
					}
				)
				.Unwrap()
				.ContinueWith(
					task2 =>
					{
						if(streamReader != null)
							streamReader.Dispose();
						string text = task2.Result;
						Console.WriteLine(
							FormatBytes(text.Length));
					}
				);

			return task;
		}
		static public string FormatBytes(long bytes)
		{
			string[] magnitudes =
				new string[] { "GB", "MB", "KB", "Bytes" };
			long max =
				(long)Math.Pow(1024, magnitudes.Length);

			return string.Format("{1:##.##} {0}",
				magnitudes.FirstOrDefault(
					magnitude =>
						bytes > (max /= 1024)) ?? "0 Bytes",
				(decimal)bytes / (decimal)max).Trim();
		}
		
		public void Test()
		{
			AsyncTest();
		}
	}
}